import DefensiveFacility from "../facility/DefensiveFacility";
import DestructibleFacility from "../facility/DestructibleFacility";
import HealthPoint from "../funcObj/interface/HealthPoint";
import GameManager from "../manager/GameManager";
import NodePoolManager from "../manager/NodePoolManager";
import Player from "../player/Player";
import Flyer from "./Flyer";

const { ccclass, property } = cc._decorator;
/**
 * 防御武器飞行物
 */
@ccclass
export abstract default class DefenseFlyer extends Flyer {

    base: DefensiveFacility;

    target: HealthPoint;

    _targetPosition: cc.Vec3;

    public get targetPosition(): cc.Vec3 {
        return this._targetPosition;
    }

    public set targetPosition(v: cc.Vec3) {
        this._targetPosition = v;
    }

    atk: number;

    init(base: DestructibleFacility, target?: HealthPoint): void {
        this.target = target;
        super.init(base, target);
    }

    public dispatch(target: HealthPoint): void {
        target.node.on(Flyer.EventType.摧毁, this.onTargetDie, this);
        target.node.on(DestructibleFacility.EventType.摧毁, this.onTargetDie, this);
    }

    onArrive() {
        if (this.target) {
            this.target.node.targetOff(this);
            let killed = this.target.reducedHp({ player: this.player, facility: this.base, domage: this.atk, flyer: this });
            if (killed && this.player) {
                this.player.node.emit(Player.EventType.击毁敌方飞行物)
            }
        }
        //获取当前位置的视野
        let location = GameManager.instance.getMapLocation(this.node.position);
        this.player.getLocationView(location);

        //清空
        this.targetPosition = null;
        this.target = null;
        this.atk = 0;
        super.onArrive();
        // 播放爆炸动画
        this.addBulletEffect();
        // 回收
        NodePoolManager.instance.recycle(this.node);
    }

    /**
     * 当目标死亡
     */
    onTargetDie() {
        this.target.node.targetOff(this);
        this.targetPosition = this.target.node.position;
        this.target = null;
    }

    /**
  * 播放子弹击中动画
  */
    addBulletEffect() {
        GameManager.instance.addBulletEffect(this.node.position);
    }
}
